import { Controller, Post, Body, Param, Get, UseGuards, Request, Query } from '@nestjs/common';
import { SubmissionService } from './submission.service';
import { CreateSubmissionDto } from './dto/create-submission.dto';
import { ProjectService } from '../project/project.service';
import { UserService } from '../user/user.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../auth/roles.guard';
import { RequireLevel } from '../auth/roles.decorator';

@Controller('submissions')
export class SubmissionController {
  constructor(
    private readonly submissionService: SubmissionService,
    private readonly projectService: ProjectService,
    private readonly userService: UserService,
  ) {}

  // 公开端点，允许匿名提交数据
  @Post('project/:projectId')
  async create(
    @Param('projectId') projectId: string,
    @Body() createSubmissionDto: CreateSubmissionDto,
  ) {
    const project = await this.projectService.findOne(parseInt(projectId, 10));
    return this.submissionService.create(createSubmissionDto, project);
  }

  // 通过分享令牌提交数据的公开端点
  @Post('share/:shareToken')
  async createFromShare(
    @Param('shareToken') shareToken: string,
    @Body() createSubmissionDto: CreateSubmissionDto,
  ) {
    return this.submissionService.createFromShare(createSubmissionDto, shareToken);
  }

  @UseGuards(JwtAuthGuard)
  @Get()
  async findAllForUser(@Request() req) {
    const user = await this.userService.findById(req.user.userId);
    if (!user) {
      throw new Error('User not found');
    }
    return this.submissionService.findAllForUser(user);
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @RequireLevel(1) // 只有最高级别管理者可以查看所有提交
  @Get('all')
  async findAll() {
    return this.submissionService.findAll();
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Get('project/:projectId')
  async findByProject(@Param('projectId') projectId: string, @Request() req) {
    const project = await this.projectService.findOne(parseInt(projectId, 10));
    // 设置资源所有者ID用于RolesGuard检查
    req.resourceOwnerId = project.owner.id;
    return this.submissionService.findAllByProject(parseInt(projectId, 10));
  }

  @UseGuards(JwtAuthGuard)
  @Get('by-recommender/:recommenderId')
  async findByRecommendedBy(
    @Param('recommenderId') recommenderId: string,
    @Request() req
  ) {
    const user = await this.userService.findById(req.user.userId);
    if (!user) {
      throw new Error('User not found');
    }
    return this.submissionService.findByRecommendedBy(parseInt(recommenderId, 10), user);
  }

  @UseGuards(JwtAuthGuard)
  @Get('filter')
  async findWithFilters(
    @Request() req,
    @Query('projectId') projectId?: string,
    @Query('recommenderId') recommenderId?: string
  ) {
    const user = await this.userService.findById(req.user.userId);
    if (!user) {
      throw new Error('User not found');
    }

    // 如果同时指定了项目和推荐管理员
    if (projectId && recommenderId) {
      return this.submissionService.findByProjectAndRecommendedBy(
        parseInt(projectId, 10),
        parseInt(recommenderId, 10),
        user
      );
    }

    // 如果只指定了推荐管理员
    if (recommenderId) {
      return this.submissionService.findByRecommendedBy(parseInt(recommenderId, 10), user);
    }

    // 如果只指定了项目
    if (projectId) {
      return this.submissionService.findAllByProject(parseInt(projectId, 10));
    }

    // 如果都没指定，返回用户可见的所有数据
    return this.submissionService.findAllForUser(user);
  }
}